<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>抖音视频下载器 - 调试工具</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        h1, h2 {
            color: #333;
            border-bottom: 2px solid #007cba;
            padding-bottom: 10px;
        }
        .status {
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
        }
        .success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
        .warning { background-color: #fff3cd; color: #856404; border: 1px solid #ffeaa7; }
        .info { background-color: #d1ecf1; color: #0c5460; border: 1px solid #bee5eb; }
        button {
            background-color: #007cba;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover { background-color: #005a87; }
        button:disabled { background-color: #ccc; cursor: not-allowed; }
        .log-container {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 15px;
            max-height: 400px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 12px;
        }
        .url-test {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            margin: 10px 0;
        }
        input[type="url"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin: 5px 0;
        }
        .test-result {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔧 抖音视频下载器调试工具</h1>
        <div id="extensionStatus" class="status info">正在检查插件状态...</div>
    </div>

    <div class="container">
        <h2>📊 插件状态检查</h2>
        <button onclick="checkExtensionStatus()">检查插件状态</button>
        <button onclick="checkPermissions()">检查权限</button>
        <button onclick="testDownloadAPI()">测试下载API</button>
        <div id="statusResults"></div>
    </div>

    <div class="container">
        <h2>🔍 URL测试工具</h2>
        <div class="url-test">
            <label for="testUrl">测试视频URL:</label>
            <input type="url" id="testUrl" placeholder="输入要测试的视频URL..." 
                   value="https://v3-web-prime.douyinvod.com/video/tos/cn/tos-cn-ve-15c001-alinc2/oUfNAeQIgDEBEXnfbAzEA6BIgNEfQgEeE/?a=6383">
            <button onclick="testURL()">测试URL</button>
            <button onclick="testDownload()">测试下载</button>
            <div id="urlTestResult" class="test-result"></div>
        </div>
    </div>

    <div class="container">
        <h2>📋 实时日志</h2>
        <button onclick="clearLogs()">清空日志</button>
        <button onclick="exportLogs()">导出日志</button>
        <div id="logContainer" class="log-container"></div>
    </div>

    <script>
        let logs = [];

        function addLog(message, type = 'info') {
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = {
                timestamp,
                message,
                type,
                time: Date.now()
            };
            logs.push(logEntry);
            
            const container = document.getElementById('logContainer');
            const div = document.createElement('div');
            div.className = `log-entry log-${type}`;
            div.textContent = `[${timestamp}] ${message}`;
            container.appendChild(div);
            container.scrollTop = container.scrollHeight;
        }

        function clearLogs() {
            logs = [];
            document.getElementById('logContainer').innerHTML = '';
        }

        function exportLogs() {
            const logText = logs.map(log => `[${log.timestamp}] ${log.type.toUpperCase()}: ${log.message}`).join('\n');
            const blob = new Blob([logText], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `douyin-plugin-logs-${Date.now()}.txt`;
            a.click();
            URL.revokeObjectURL(url);
        }

        async function checkExtensionStatus() {
            const statusDiv = document.getElementById('statusResults');
            statusDiv.innerHTML = '';
            
            addLog('开始检查插件状态...', 'info');
            
            // 检查Chrome扩展API
            if (typeof chrome === 'undefined') {
                addLog('❌ Chrome扩展API不可用', 'error');
                statusDiv.innerHTML += '<div class="status error">Chrome扩展API不可用</div>';
                return;
            }
            
            addLog('✅ Chrome扩展API可用', 'info');
            statusDiv.innerHTML += '<div class="status success">Chrome扩展API可用</div>';
            
            // 检查runtime
            if (!chrome.runtime) {
                addLog('❌ chrome.runtime不可用', 'error');
                statusDiv.innerHTML += '<div class="status error">chrome.runtime不可用</div>';
                return;
            }
            
            addLog('✅ chrome.runtime可用', 'info');
            statusDiv.innerHTML += '<div class="status success">chrome.runtime可用</div>';
            
            // 测试与background的通信
            try {
                const response = await chrome.runtime.sendMessage({type: 'GET_VIDEO_URLS'});
                addLog('✅ Background通信成功', 'info');
                addLog(`返回数据: ${JSON.stringify(response)}`, 'info');
                statusDiv.innerHTML += '<div class="status success">Background通信正常</div>';
            } catch (error) {
                addLog(`❌ Background通信失败: ${error.message}`, 'error');
                statusDiv.innerHTML += `<div class="status error">Background通信失败: ${error.message}</div>`;
            }
        }

        async function checkPermissions() {
            const statusDiv = document.getElementById('statusResults');
            
            addLog('检查权限...', 'info');
            
            // 检查downloads权限
            if (chrome.downloads) {
                addLog('✅ downloads权限可用', 'info');
                statusDiv.innerHTML += '<div class="status success">downloads权限可用</div>';
            } else {
                addLog('❌ downloads权限不可用', 'error');
                statusDiv.innerHTML += '<div class="status error">downloads权限不可用</div>';
            }
            
            // 检查webRequest权限
            if (chrome.webRequest) {
                addLog('✅ webRequest权限可用', 'info');
                statusDiv.innerHTML += '<div class="status success">webRequest权限可用</div>';
            } else {
                addLog('❌ webRequest权限不可用', 'error');
                statusDiv.innerHTML += '<div class="status error">webRequest权限不可用</div>';
            }
        }

        async function testDownloadAPI() {
            const statusDiv = document.getElementById('statusResults');
            
            addLog('测试下载API...', 'info');
            
            try {
                // 测试一个简单的下载
                const testUrl = 'data:text/plain;charset=utf-8,测试文件内容';
                const downloadId = await chrome.downloads.download({
                    url: testUrl,
                    filename: 'test-download.txt',
                    saveAs: false
                });
                
                addLog(`✅ 下载API测试成功，下载ID: ${downloadId}`, 'info');
                statusDiv.innerHTML += '<div class="status success">下载API测试成功</div>';
                
                // 清理测试文件
                setTimeout(() => {
                    chrome.downloads.cancel(downloadId);
                }, 1000);
                
            } catch (error) {
                addLog(`❌ 下载API测试失败: ${error.message}`, 'error');
                statusDiv.innerHTML += `<div class="status error">下载API测试失败: ${error.message}</div>`;
            }
        }

        function testURL() {
            const url = document.getElementById('testUrl').value;
            const resultDiv = document.getElementById('urlTestResult');
            
            if (!url) {
                resultDiv.innerHTML = '<div class="status error">请输入URL</div>';
                return;
            }
            
            addLog(`测试URL: ${url}`, 'info');
            
            // 测试URL格式
            try {
                const urlObj = new URL(url);
                addLog(`✅ URL格式有效: ${urlObj.href}`, 'info');
                resultDiv.innerHTML = '<div class="status success">URL格式有效</div>';
                
                // 检查是否是视频URL
                if (url.includes('.mp4') || url.includes('video') || url.includes('douyinvod.com')) {
                    addLog('✅ 检测到视频URL特征', 'info');
                    resultDiv.innerHTML += '<div class="status success">检测到视频URL特征</div>';
                } else {
                    addLog('⚠️ 未检测到明显的视频URL特征', 'warn');
                    resultDiv.innerHTML += '<div class="status warning">未检测到明显的视频URL特征</div>';
                }
                
            } catch (error) {
                addLog(`❌ URL格式无效: ${error.message}`, 'error');
                resultDiv.innerHTML = `<div class="status error">URL格式无效: ${error.message}</div>`;
            }
        }

        async function testDownload() {
             const url = document.getElementById('testUrl').value;
             const resultDiv = document.getElementById('urlTestResult');
             
             if (!url) {
                 resultDiv.innerHTML = '<div class="status error">请输入URL</div>';
                 return;
             }
             
             addLog(`测试下载: ${url}`, 'info');
             
             // 先检查URL内容类型
             try {
                 addLog('检查URL内容类型...', 'info');
                 const response = await fetch(url, { method: 'HEAD' });
                 const contentType = response.headers.get('content-type');
                 const contentLength = response.headers.get('content-length');
                 const finalUrl = response.url;
                 
                 addLog(`Content-Type: ${contentType}`, 'info');
                 addLog(`Content-Length: ${contentLength}`, 'info');
                 addLog(`Final URL: ${finalUrl}`, 'info');
                 
                 if (contentType && (contentType.includes('text/') || contentType.includes('application/javascript'))) {
                     addLog(`❌ URL指向的不是视频文件: ${contentType}`, 'error');
                     resultDiv.innerHTML = `<div class="status error">URL指向的不是视频文件，内容类型: ${contentType}</div>`;
                     return;
                 }
                 
                 // 如果内容类型检查通过，继续下载测试
                 const downloadResponse = await chrome.runtime.sendMessage({
                     action: 'DOWNLOAD_VIDEO',
                     url: finalUrl,
                     filename: '测试视频'
                 });
                 
                 if (downloadResponse && downloadResponse.success) {
                     addLog(`✅ 下载测试成功: ${downloadResponse.fileName}`, 'info');
                     addLog(`Content-Type: ${downloadResponse.contentType}`, 'info');
                     resultDiv.innerHTML = `<div class="status success">下载测试成功: ${downloadResponse.fileName}<br>内容类型: ${downloadResponse.contentType}</div>`;
                 } else {
                     addLog(`❌ 下载测试失败: ${downloadResponse?.error || '未知错误'}`, 'error');
                     resultDiv.innerHTML = `<div class="status error">下载测试失败: ${downloadResponse?.error || '未知错误'}</div>`;
                 }
                 
             } catch (error) {
                 addLog(`❌ 下载测试异常: ${error.message}`, 'error');
                 resultDiv.innerHTML = `<div class="status error">下载测试异常: ${error.message}</div>`;
             }
         }

        // 页面加载时自动检查状态
        window.addEventListener('load', () => {
            addLog('调试工具已加载', 'info');
            checkExtensionStatus();
        });

        // 监听来自插件的消息
        if (typeof chrome !== 'undefined' && chrome.runtime) {
            chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
                addLog(`收到插件消息: ${JSON.stringify(message)}`, 'info');
            });
        }
    </script>
</body>
</html>